﻿using System;
using System.Collections.Generic;
using UnityEngine;
using Yoozoo.Framework.Core;

namespace Gameplay.PVE.Survivor
{
    public class BulletManager: BattleSingleton<BulletManager>
    {
        private List<Bullet> bulletList = new List<Bullet>();
        
        public Bullet CreateBullet(BulletConfig config)
        {
            var bullet = BattleFactory.Instance.CreateBullet(config);
            bulletList.Add(bullet);
            return bullet;
        }
        
        public override void Update()
        {
            try
            {
                for (int i = 0; i < bulletList.Count; i++)
                {
                    var cell = bulletList[i];
                    cell.Update();
                    if (cell.NeedDispose())
                    {
                        cell.Dispose();
                        //跟最后一个元素交换位置
                        if (i != bulletList.Count - 1)
                        {
                            bulletList[i] = bulletList[bulletList.Count - 1];
                            i--;
                        }
                        bulletList.RemoveAt(bulletList.Count - 1);
                        BattleFactory.Instance.DestroyBullet(cell);
                    }
                }
            }
            catch (Exception e)
            {
                BattleDebug.LogError(e);
            }
            
        }

        public override void Dispose()
        {
            for (int i = 0; i < bulletList.Count; i++)
            {
                var cell = bulletList[i];
                cell.Dispose();
                BattleFactory.Instance.DestroyBullet(cell);
            }
            bulletList.Clear();
        }
    }
}
